package com.hjt.gulimall.order.config;

import com.hjt.gulimall.order.constant.RabbitMqConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:97007
 * @date:2021/10/8 16:03
 */
@Configuration
public class RabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct // 在配置类构造器完成后执行
    public void initRabbitTemplate() {
        // ConfirmCallback
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 只要消息抵达broker，就会触发回调
             * @param correlationData 当前消息的唯一关联数据（消息的唯一id）,在发送消息时指定
             * @param ack 消息是否成功被收到
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println(correlationData);
                System.out.println(ack);
                System.out.println(cause);
            }
        });
        // ReturnCallback
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递给指定的队列，就会触发失败回调
             * @param message 投递失败的消息
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange 当时消息发送给的交换机
             * @param routingKey 当时消息发送时的路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                // 消息投递失败，修改数据库中的消息状态
            }
        });
    }

    // 使用json序列化消息
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 容器中的queue、binding、exchange，如果rabbitmq中没有，会创建
     * 延迟消息队列
     * @return
     */
    @Bean
    public Queue orderDelayQueue() {
        /**
         * x-dead-letter-exchange: user.order.exchange  指定的死信交换机
         * x-dead-letter-routing-key: order 死信路由
         * x-message-ttl: 60000 消息过期时间
         */
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", RabbitMqConstant.ORDER_EVENT_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", RabbitMqConstant.ORDER_RELEASE_ROUTE_KEY); // 指定路由键
        arguments.put("x-message-ttl", 60000);
        return new Queue(RabbitMqConstant.ORDER_DELAY_QUEUE_NAME, true, false, false,arguments);
    }

    // 订单释放 的消息队列
    @Bean
    public Queue orderReleaseQueue() {
        Queue queue = new Queue(RabbitMqConstant.ORDER_RELEASE_QUEUE_NAME, true, false, false);
        return queue;
    }

    // 交换机
    @Bean
    public Exchange orderEventExchange() {
        return new TopicExchange(RabbitMqConstant.ORDER_EVENT_EXCHANGE_NAME, true, false);
    }

    // 绑定关系 order-event-exchange ---(order.create.order)---> order.delay.queue
    @Bean
    public Binding orderCreateBinding() {
        return new Binding(RabbitMqConstant.ORDER_DELAY_QUEUE_NAME, Binding.DestinationType.QUEUE,
                RabbitMqConstant.ORDER_EVENT_EXCHANGE_NAME,RabbitMqConstant.ORDER_CREATE_ROUTE_KEY,null);
    }
    // 绑定关系 order-event-exchange ---(order.release.order)---> order.release.queue
    @Bean
    public Binding orderReleaseBinding() {
        return new Binding(RabbitMqConstant.ORDER_RELEASE_QUEUE_NAME, Binding.DestinationType.QUEUE,
                RabbitMqConstant.ORDER_EVENT_EXCHANGE_NAME,RabbitMqConstant.ORDER_RELEASE_ROUTE_KEY,null);
    }

    /**
     * 订单释放直接和库存释放绑定，确保订单关闭后，库存解锁
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding(RabbitMqConstant.STOCK_RELEASE_QUEUE_NAME, Binding.DestinationType.QUEUE,
                        RabbitMqConstant.ORDER_EVENT_EXCHANGE_NAME,RabbitMqConstant.ORDER_STOCK_ROUTE_KEY,null);
    }


}
